package common.util;

import org.apache.commons.lang3.SerializationUtils;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Supplier;

/**
 * @Author wangyue
 * @Version 3.0
 * @Date 2023-11-07
 */
public class SimplestCache<K> extends LinkedHashMap<K, Object> {

    int sizeLimit = -1;

    public SimplestCache() {
        super();
    }

    public SimplestCache(int sizeLimit) {
        super();
        this.sizeLimit = sizeLimit;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, Object> eldest) {
        return sizeLimit > 0 && size() > sizeLimit;
    }

    public <V> V get(K key, Supplier<V> supplier) {
        V value = (V)super.get(key);
        if(value == null) {
            value = supplier.get();
            put(key, (Object)value);
        }
        return value;
    }

    public <V extends Serializable> V getCloned(K key, Supplier<V> supplier) {
        return SerializationUtils.clone(get(key, supplier));
    }

}
